package com.dormitory_springboot.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dormitory_springboot.entity.Notices;
import com.dormitory_springboot.service.NoticesService;
import com.dormitory_springboot.util.ResultVOUtil;
import com.dormitory_springboot.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-01-14
 */
@RestController
@RequestMapping("/notices")
public class NoticesController {

    @Autowired
    private NoticesService noticesService;

    // 新增或者更新
    @PostMapping
    public ResultVO save(@RequestBody Notices notices) {
        if (notices.getId() == null) {
            notices.setTime(DateUtil.now());
//            notices.setUser(TokenUtils.getCurrentUser().getNickname());
        }
        noticesService.saveOrUpdate(notices);
        return ResultVOUtil.success(null);
    }

    @DeleteMapping("/{id}")
    public ResultVO delete(@PathVariable Integer id) {
        noticesService.removeById(id);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/del/batch")
    public ResultVO deleteBatch(@RequestBody List<Integer> ids) {
        noticesService.removeByIds(ids);
        return ResultVOUtil.success(null);
    }

    @GetMapping
    public ResultVO findAll() {
        return ResultVOUtil.success(noticesService.list());
    }

    /**
     * 根据类型查询公告
     *
     * @param type
     * @return
     */
    @GetMapping("/type/{type}")
    public ResultVO findByType(@PathVariable Integer type) {
        QueryWrapper<Notices> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.orderByDesc("time"); // 按时间降序排列
        return ResultVOUtil.success(noticesService.list(queryWrapper));
    }

    @GetMapping("/{id}")
    public ResultVO findOne(@PathVariable Integer id) {
        return ResultVOUtil.success(noticesService.getById(id));
    }

    @GetMapping("/page")
    public ResultVO findPage(@RequestParam(defaultValue = "") String name,
                             @RequestParam(required = false) Integer type,
                             @RequestParam Integer pageNum,
                             @RequestParam Integer pageSize) {
        QueryWrapper<Notices> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("type", type);
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
//        User currentUser = TokenUtils.getCurrentUser();
//        if (currentUser.getRole().equals("ROLE_USER")) {
//            queryWrapper.eq("user", currentUser.getUsername());
//        }
        return ResultVOUtil.success(noticesService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

